﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace Common.Helpers
{
    public class CryptographyHelper
    {
        public string EncrytpPassword(string input)
        {
            var mdcsp = new MD5CryptoServiceProvider();
            byte[] b = Encoding.UTF8.GetBytes(input);
            b = mdcsp.ComputeHash(b);
            var sb = new StringBuilder();
            foreach (byte by in b)
            {
                sb.Append(by.ToString("x2").ToLower());
            }
            return sb.ToString();
        }

        //public static string EncodeTo64(string toEncode)
        //{
        //    byte[] toEncodeAsBytes
        //          = Encoding.UTF8.GetBytes(toEncode);
        //    string returnValue
        //          = System.Convert.ToBase64String(toEncodeAsBytes);
        //    return returnValue;
        //}

        //public static string DecodeFrom64(string encodedData)
        //{
        //    byte[] encodedDataAsBytes
        //        = System.Convert.FromBase64String(encodedData);
        //    string returnValue =
        //       Encoding.UTF8.GetString(encodedDataAsBytes);
        //    return returnValue;
        //}

        public static string Base64Encode(string data)
        {
            try
            {
                byte[] encDataByte = Encoding.UTF8.GetBytes(data);
                string encodedData = Convert.ToBase64String(encDataByte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode" + e.Message);
            }
        }

        public static string Base64Decode(string data)
        {
            try
            {
                var encoder = new UTF8Encoding();
                var utf8Decode = encoder.GetDecoder();

                byte[] todecodeByte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecodeByte, 0, todecodeByte.Length);
                var decodedChar = new char[charCount];
                utf8Decode.GetChars(todecodeByte, 0, todecodeByte.Length, decodedChar, 0);
                var result = new String(decodedChar);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode" + e.Message);
            }
        }
    }
}
